﻿//----------------------------------------------------------------
// Copyright (c) 2011-2013 
// All rights reserved.
// Author: Ben DaoWei 
// Contact: bendaowei@gmail.com
// Web Link: http://xnaeditor.codeplex.com
// ----------------------------------------------------------------

using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using System;
using System.IO;
using Microsoft.Xna.Framework.Graphics;
using UnityEngine.IO;
using MdxLib.Model;

namespace UnityEngine.Graphics
{
    public class CustomPaletteRenderContainer : PaletteRendererContainer
    {
        private static Game _Game;

        private static List<string> _DebugRecords;

        private static Dictionary<string, ModelRenderer> _CustomRenderer;

        public CustomPaletteRenderContainer(Game game)
        {
            _Game = game;
            _CustomRenderer = new Dictionary<string, ModelRenderer>();
            _DebugRecords = new List<string>();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_CustomRenderer != null)
                {
                    foreach (var unit in _CustomRenderer.Values)
                        if (unit != null)
                            unit.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        public void AddCustomRenderer(string name, string ModelName, Game game)
        {
            if (_CustomRenderer.ContainsKey(name) == true)
                return;

            if (String.IsNullOrEmpty(ModelName))
            {
                _CustomRenderer.Add(name, new UnitRenderer(null, null));
            }
            else
            {
                //if (Path.HasExtension(ModelName))
                //    ModelName = ModelName.Substring(0, ModelName.IndexOf("."));

                CModel model = ModelRenderer.LoadCModel(IOManager.Instance.GetAssertPath(ModelName));
                //MDX.Model model = game.Content.Load<MDX.Model>(ModelName);
                _CustomRenderer.Add(name, new ModelRenderer(game.GraphicsDevice, model));
            }
        }

        public override PaletteRenderer GetPaletteRenderer(string name)
        {
            if (_CustomRenderer.ContainsKey(name) == false)
            {
                if (_DebugRecords.Contains(name) == false)
                    _DebugRecords.Add(name);
                this.AddCustomRenderer(name, name, _Game);
                return _CustomRenderer[name];
            }

            return _CustomRenderer[name];
        }

        public static void PrintDebugRecords()
        {
            _DebugRecords.Sort();
            for (int i = 0; i < _DebugRecords.Count; i++)
                Debug.WriteLine(_DebugRecords[i]);
        }
    }
}
